
package com.itcs.pap.tran;

import com.alibaba.fastjson.JSON;
import com.itcs.box.BoxConstants;
import com.itcs.box.domain.BoxRequest;
import com.itcs.box.util.LogUtils;
import com.itcs.eureka.service.PayApiFeignClientService;
import com.itcs.trading.mapper.TerminalInfoMapper;
import com.itcs.trading.mapper.TerminalLinksRgtMapper;
import com.itcs.trading.model.TerminalInfo;
import com.itcs.trading.model.TerminalLinksRgt;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName: Tran1002
 * @Description: 心跳状态信息
 * @author CHEN-HF
 * @date 2017年12月19日 下午8:47:45
 * 
 */
@Component
public class BoxTran1002 implements PayApiFeignClientService {

	@Autowired
	private TerminalInfoMapper terminalInfoMapper;

	@Autowired
	private TerminalLinksRgtMapper terminalLinksRgtMapper;

	private Log logger = LogFactory.getLog(getClass());

	@Override
	public String getTrancode() {
		return "box_1002";
	}

	public String getTranDescription() {
		return "心跳状态信息";
	}

	@Override
	@RequestMapping(value = "/box_1002", method = RequestMethod.POST, produces = "application/json")
	public Map<String, Object> exchange(String serverId, String trancode,
										@RequestParam Map<String, Object> reqRecord) {

		Map<String, Object> res = new HashMap<>();
		BoxRequest boxRequest = null;
		try {
			boxRequest = (BoxRequest) reqRecord.get(BoxConstants.BOX_REQ_KEY);
			// 业务处理
			this.handle(boxRequest);
		} catch (Exception e) {
			// 其他异常或数据库异常
			res.put("result", "-2");
			logger.error(LogUtils.build(getTrancode(), getTranDescription(), "处理失败" + e.getMessage(),
					JSON.toJSONString(reqRecord)), e);
		}

		return res;
	}

	public void handle(BoxRequest boxRequest) {

		// 数据库查找道路、设备
		TerminalInfo lane = terminalInfoMapper.selectByDeviceId(boxRequest.getData().getDeviceId());
		if (lane != null && lane.getLaneId() != null) {
			// 更新盒子信息
			// 根据盒子序列号查询最新更新信息
			TerminalLinksRgt link = terminalLinksRgtMapper.selectByPrimaryKey(boxRequest.getChannelId());
			if (link == null) {
				logger.error(LogUtils.build(getTrancode(), getTranDescription(),
						"未找到通讯盒连接通道，可能已经掉线:" + boxRequest.getData().getDeviceId(),
						JSON.toJSONString(boxRequest)));
			} else {
				link.setLinkHbTime(new Date());
				link.setTerminalStatus(Integer.parseInt(boxRequest.getData().getStatus()));

				terminalLinksRgtMapper.updateByPrimaryKey(link);
			}

		} else {
			logger.error(LogUtils.build(getTrancode(), getTranDescription(),
					"未找到通讯盒:" + boxRequest.getData().getDeviceId(), JSON.toJSONString(boxRequest)));
		}
	}

}
